//
//  HRRefreshControl.swift
//  microBlog
//
//  Created by HR_W on 16/5/27.
//  Copyright © 2016年 admin. All rights reserved.
//

import UIKit

enum RefreshStatue: Int {
    case Normal
    case Pulling
    case Refreshing
}

private let refreshViewHeight: CGFloat = 60

class HRRefreshControl: UIControl {

    var statue: RefreshStatue = .Normal{
    
        didSet {
        
            switch statue {
            case .Normal:
                arrowicon.hidden = false
                indicatorView.stopAnimating()
                tipLabel.text = "下拉起飞"
                UIView.animateWithDuration(0.25, animations: { 
                    self.arrowicon.transform = CGAffineTransformIdentity
                })
                if oldValue == .Refreshing{
                
                UIView.animateWithDuration(0.25, animations: { 
                    var inset = self.scrollView?.contentInset
                    inset?.top -= refreshViewHeight
                    
                    self.scrollView?.contentInset = inset!
                })
                
                }
            case .Pulling:
                tipLabel.text = "准备起飞"
                UIView.animateWithDuration(0.25, animations: { 
                    self.arrowicon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case.Refreshing:
                tipLabel.text = "正在起飞"
                arrowicon.hidden = true
                indicatorView.startAnimating()
                sendActionsForControlEvents(.ValueChanged)
                
                UIView.animateWithDuration(0.25, animations: { 
                    var inset = self.scrollView?.contentInset
                    inset!.top += refreshViewHeight
                    
                    self.scrollView?.contentInset = inset!
                })
            }
        }
    
    }
    func endRefreshing() {
        let time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 0.6))
        dispatch_after(time_t, dispatch_get_main_queue()) { 
            self.statue = .Normal
        }
    }
    
    var scrollView: UIScrollView?
    override init(frame: CGRect) {
    let rect = CGRect(x: 0, y: -refreshViewHeight, width: ScreenWidth, height: refreshViewHeight)
        super.init(frame: rect)
        backgroundColor = UIColor.greenColor()
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        let offSetY = scrollView?.contentOffset.y ?? 0
        if scrollView!.dragging {
            
            if statue == .Pulling && offSetY > -124{
                statue = .Normal
            }else if statue == .Normal && offSetY < -124{
            
                statue = .Pulling
            }
        }else{
        
            if statue == .Pulling {
                
                statue = .Refreshing
            }
        }
        
        
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        
        if let myFather = newSuperview as? UIScrollView{
          
            scrollView = myFather
            scrollView?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
        }
    }
    
   
    private func setupUI() {
        addSubview(arrowicon)
        addSubview(tipLabel)
        addSubview(indicatorView)
        
        arrowicon.snp_makeConstraints { (make) -> Void in
            //水平居中 向左偏移 30
            make.centerX.equalTo(self.snp_centerX).offset(-30)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        tipLabel.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(arrowicon.snp_right)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        
        indicatorView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowicon.snp_center)
        }
    }

    
    private lazy var arrowicon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    private lazy var tipLabel: UILabel = UILabel(titie: "下拉起飞", font: 14, textColor: UIColor.darkGrayColor())
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
    
    deinit{
    
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
}
